package db;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.*;

import org.apache.commons.beanutils.BeanUtils;
public class BeanUtilities {

	public static void populateBean(Object bean, Map propertyMap) {
		Map propertyMap1 = null;
		try {
			BeanUtils.populate(bean, propertyMap);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
	
	public static void populateBean(Object bean, Map propertyMap, HttpServletRequest request, HttpServletResponse response,
			String red) {
		Map propertyMap1 = null;
		try {
			if(propertyMap.containsKey("data")) {
				
				String[] data = (String[]) propertyMap.get("data");
		
				if( data != null) {
						String[] dateS = data[0].split("-");
						Date d = new Date();
						//deprecated ale lepiej dziala ten obiekt z sql
						int year = Integer.parseInt(dateS[0]) - 1900 ;
						int month = Integer.parseInt(dateS[1]) -1;
						int day = Integer.parseInt(dateS[2]);
						d.setYear(year);
						if(month > 0 && month < 12) {
							d.setMonth(month);
						}
						if(day >0 && day< 32) {
							d.setDate(day);
						}
						
						if(propertyMap.containsKey("time")) {
							
							String[] time = (String[]) propertyMap.get("time");
							
							if( time != null) {
								String[] timeS = time[0].split(":");
								int hours = Integer.parseInt(timeS[0]);
								int minutes = Integer.parseInt(timeS[1]);
								if(hours >= 0 && hours < 24) {
									d.setHours(hours);
								}
								if(minutes >= 0 && minutes < 60) {
									d.setMinutes(minutes);
								}
							}
							
							
						}
						propertyMap1 = new HashMap();
						propertyMap1.putAll(propertyMap);
						propertyMap1.remove("data");
						propertyMap1.put("data", d);
				}
		
				
			}
			if(propertyMap1 != null) {
				propertyMap = propertyMap1;
			}
			BeanUtils.populate(bean, propertyMap);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}
